package com.founder.gateway.oauth.service.impl;

import com.founder.gateway.oauth.orm.orcl.bean.entity.OrgUserEntity;
import com.founder.gateway.oauth.service.OAuthService;
import com.founder.gateway.orm.fzapi.bean.entity.AppInfoEntity;
import com.founder.oauth.expand.ClientQueryService;
import com.founder.oauth.expand.UserQueryService;
import com.founder.oauth.utils.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;

@Service
public class OAuthQueryServiceImpl implements UserQueryService, ClientQueryService {
    @Resource
    private OAuthService oAuthService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        OrgUserEntity entity = oAuthService.getUserByIdentity(username);
        if (entity == null) {
            throw new UsernameNotFoundException("未找到用户：" + username);
        }
        return new User(entity.getUserid(), "{MD5}" + entity.getPassword(), AuthorityUtils.createAuthorityList(AuthorityUtils.ROLE_USER));
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        AppInfoEntity entity = oAuthService.getClientByAppKey(clientId);
        if (entity == null) {
            throw new NoSuchClientException("未找到客户端： " + clientId);
        }
        return newClientCredentials(entity);
    }

    private ClientDetails newClientCredentials(AppInfoEntity entity) {
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(entity.getAppKey());
        clientDetails.setClientSecret(entity.getAppSecrect());
        clientDetails.setAccessTokenValiditySeconds(entity.transfer().getTokenExpiration());
        clientDetails.setAuthorities(AuthorityUtils.createAuthorityList(AuthorityUtils.ROLE_CLIENT));
        clientDetails.setAuthorizedGrantTypes(Collections.singleton("client_credentials"));
        clientDetails.setScope(Collections.singleton("user_info"));
        return clientDetails;
    }
}
